var HtmlParser = require('htmlParseUtil.js');
var html2jsoner = require('../wxParse/html2json.js')
var host = "https://api.biquge.bukaa.cn/";

String.prototype.trim = function () {
  return this.replace(/(^\s*)|(\s*$)/g, '');
}

String.prototype.isEmpty = function () {
  return this.trim() == '';
}

function getHost(){
  return host;
}

function formatTime(date) {
  var year = date.getFullYear()
  var month = date.getMonth() + 1
  var day = date.getDate()
  var hour = date.getHours()
  var minute = date.getMinutes()
  var second = date.getSeconds()
  return [year, month, day].map(formatNumber).join('/') + ' ' + [hour, minute, second].map(formatNumber).join(':')
}

function formatNumber(n) {
  n = n.toString()
  return n[1] ? n : '0' + n
}

/**
 * 获取当前日期对象
 * @returns {object}
 */
function getCurrentData() {
  var date = new Date();
  return {
    date: new Date(),
    year: date.getFullYear(),
    month: date.getMonth() + 1,
    day: date.getDate(),
    weekday: date.getDay()
  };
}

/**
 * 快捷方法 获取HtmlParser对象
 * @param {string} html html文本
 * @return {object} HtmlParser
 */
function $(html) {
  return new HtmlParser(html);
}

/**
 * 解析分类列表
 * @param {string} html body的html文本
 * @param {boolean} isDecode 是否需要unicode解析
 * @return {object} 解析后的对象
 */
function parseSortList(html, isDecode) {
  var resultArr = $(html).tag('div').attr('class', 'ptm-card-content').match();
  if (!resultArr) return;
  resultArr = $(resultArr[1]).tag('li').match();
  var stories = [];
  var $story;
  if (resultArr) {
    for (var i = 0, len = resultArr.length; i < len; i++) {
      $story = $(resultArr[i]);
      stories.push({
        index: i,
        type: $story.tag('a').match()[3],
        title: $story.tag('a').match()[1],
        author: $story.tag('a').match()[2],
        brief: $story.tag('div').attr('class', 'pt-desc ptm-text-cut').match()[0],
        img: host + getArrayContent($story.tag('div').attr('class', 'pt-cover').match()[0].jhe_ma('img','src')),
        href: host + getArrayContent($story.tag('div').match()[0].jhe_ma('a', 'href'))
      });
    }
  }
  return stories;
}

/**
 * 解析分类列表
 * @param {string} html body的html文本
 * @param {boolean} isDecode 是否需要unicode解析
 * @return {object} 解析后的对象
 */
function parseSearchResultList(html, isDecode) {
  var resultArr = $(html).tag('div').attr('class', 'ptm-card-content').match();
  if (!resultArr) return;
  resultArr = $(resultArr[1]).tag('li').match();
  var stories = [];
  var $story;
  if (resultArr) {
    for (var i = 0, len = resultArr.length; i < len; i++) {
      $story = $(resultArr[i]);
      stories.push({
        index: i,
        type: "--",
        title: getArrayContent($story.tag('a').match()[0].jhe_ma('img', 'alt')),
        author: "--",
        brief: "点击即可查看改小说的详细内容！",
        img: host + getArrayContent($story.tag('div').match()[0].jhe_ma('img', 'src')),
        href: host + getArrayContent($story.tag('div').match()[0].jhe_ma('a', 'href'))
      });
    }
  }
  return stories;
}

/**
 * 解析小说主页
 * @param {string} html body的html文本
 * @return {object} 解析后的对象
 */
function parseNovel(html, $this) {
  var $html = $(html);
  //1、小说信息
  console.time("step:1");
  wx.showLoading({title: '解析基本信息'})
  var novel = {};
  var baseinfo = $html.tag('div').attr('class', 'baseinfo').match();
  var img = host + getArrayContent(baseinfo[0].jhe_ma('img', 'src'));
  var $baseinfo = $(baseinfo[0]);
  var title = $baseinfo.tag('a').match()[0];
  wx.setNavigationBarTitle({ title: title })
  var author = $baseinfo.tag('a').match()[1];
  var type = $baseinfo.tag('a').match()[2];
  var updateTime = $($baseinfo.tag('div').attr('class', 'pt-novel').match()[0]).tag('div').match()[2];
  var popularity = $($baseinfo.tag('div').attr('class', 'pt-novel').match()[0]).tag('div').match()[3];
  novel = {
    title: title || '未知',
    img: img,
    author: author || '',
    type: type,
    updateTime: updateTime || '更新：未知',
    popularity: popularity || '人气：未知',
  };
  $this.setData({novel: novel});
  console.timeEnd("step:1");
  //2、简介
  wx.showLoading({ title: '解析简介' })
  console.time("step:2");
  var intro = getArrayContent($html.tag('div').attr('class', 'intro').match());
  novel['intro'] = intro || '暂无简介';
  $this.setData({ novel: novel });
  console.timeEnd("step:2");
  //3、最新章节列表
  wx.showLoading({ title: '解析最新章节' })
  console.time("step:3");
  var newC = $html.tag('ul').attr('id', 'newchaperlist').match();
  var newChArr = [];
  if(newC){
    var newArr = $(newC[0]).tag('li').match();
    for (var i = 0, len = newArr.length; i < len; i++) {
        var ch = {};
        ch['href'] = host + newArr[i].jhe_ma('a', 'href');
        ch['title'] = getArrayContent($(newArr[i]).tag('a').match());
        newChArr.push(ch);
    }
  }
  novel['newChArr'] = newChArr;
  $this.setData({novel: novel});
  wx.hideLoading();
  console.timeEnd("step:3");
  //4、所有章节列表
  console.time("step:4");
  //wx.showLoading({ title: '解析全部章节' })
  var allC = $html.tag('ul').attr('id', 'chapterlist').match();
  var allChArr = [];
  if (allC) {
    var allArr = $(allC[0]).tag('li').match();
    for (var i = 0, len = allArr.length; i < len; i++) {
      var ch = {};
      ch['href'] = host + allArr[i].jhe_ma('a', 'href');
      ch['title'] = getArrayContent($(allArr[i]).tag('a').match());
      allChArr.push(ch);
    }
  }
  console.timeEnd("step:4");
  var novel = {
    title: title||'未知',
    img: img,
    author: author||'',
    type: type,
    updateTime: updateTime || '更新：未知',
    popularity: popularity || '人气：未知',
    intro: intro || '暂无简介',
    newChArr: newChArr,
    allChArr: allChArr
  };
  //wx.showLoading({ title: '全部数据解析成功' })
  return novel;
}



/**
 * 解析文章内容
 * @param {string} $story htmlparser对象
 * @param {boolean} isDecode 是否需要unicode解析
 * @returb {object} 文章内容对象
 */
function parseStoryContentFetchParam(html, isDecode) {
  var scrpits = $(html).tag('script').match();
  var article_id, chapter_id, hash;
  var article_id_reg = /var article_id = \"([^\"]*?)\"/gi;
  var article_id_reg_result = html.match(article_id_reg);
  if (article_id_reg_result){
    article_id = RegExp.$1;
  }
  var chapter_id_reg = /var chapter_id = \"([^\"]*?)\"/gi;
  var chapter_id_reg_result = html.match(chapter_id_reg);
  if (chapter_id_reg_result) {
    chapter_id = RegExp.$1;
  }
  var hash_reg = /var hash = \"([^\"]*?)\"/gi;
  var hash_reg_result = html.match(hash_reg);
  if (hash_reg_result) {
    hash = RegExp.$1;
  }
  var url = getHost() + "/home/index/ajaxchapter";
  var data = { article_id: article_id,
               chapter_id: chapter_id,
               cid: chapter_id,
               hash:hash
              };
  console.log("url====>" + url);
  return {url:url, data:data};
}

/**
 * 取出多余或者难以解析的html并且替换转义符号
 */
function decodeHtml(value, isDecode) {
  if (!value) return '';
  value = value.replace(/<[^>]+>/g, '')
    .replace(/&nbsp;/g, ' ')
    .replace(/&ldquo;/g, '"')
    .replace(/&rdquo;/g, '"').replace(/&middot;/g, '·');
  if (isDecode)
    return decodeUnicode(value.replace(/&#/g, '\\u'));
  return value;

}

/**
 * 解析段落的unicode字符，主题日报中的内容又很多是编码过的
 */
function decodeUnicode(str) {
  var ret = '';
  var splits = str.split(';');
  for (let i = 0; i < splits.length; i++) {
    ret += spliteDecode(splits[i]);
  }
  return ret;
};

/**
 * 解析单个unidecode字符
 */
function spliteDecode(value) {
  var target = value.match(/\\u\d+/g);
  if (target && target.length > 0) { //解析类似  "7.1 \u20998" 参杂其他字符
    target = target[0];
    var temp = value.replace(target, '{{@}}');
    target = target.replace('\\u', '');
    target = String.fromCharCode(parseInt(target));
    return temp.replace("{{@}}", target);
  } else {
    // value = value.replace( '\\u', '' );
    // return String.fromCharCode( parseInt( value, '10' ) )
    return value;
  }
}

/**
 * 获取数组中的内容（一般为第一个元素）
 * @param {array} arr 内容数组
 * @return {string} 内容
 */
function getArrayContent(arr, idx) {
  if (!arr || arr.length == 0) return '';
  idx = idx || 0;
  return arr[idx];
}

function isOnly(src, target) {
  return src.trim() == target;
}

/**
 * 判断目标是否是函数
 * @param {mixed} val
 * @returns {boolean}
 */
function isFunction(val) {
  return typeof val === 'function';
}

/**
 * 修正图片url，将pic1和pic2改为pic4
 * @param data
 * @returns {*}
 */
function correctData(data) {
  if (("top_stories" in data)) {
    var top_stories = data.top_stories;
    for (var i = 0; i < top_stories.length; i++) {
      top_stories[i].image = fixImgPrefix(top_stories[i].image);
    }
    data.top_stories = top_stories;
  }

  var stories = data.stories;
  for (var i = 0; i < stories.length; i++) {
    if (("images" in stories[i])) {
      var s = stories[i].images[0];
      s = fixImgPrefix(s);
      stories[i].images[0] = s;
    }
  }

  data.stories = stories;
  return data;
}

/**
 * 将转义字符转为实体
 * @param data
 * @returns {*}
 */
function transferSign(data) {
  data = data.replace(/&ndash;/g, "–");
  data = data.replace(/&mdash;/g, "—");
  data = data.replace(/&hellip;/g, "…");
  data = data.replace(/&bull;/g, "•");
  data = data.replace(/&rsquo;/g, "’");
  data = data.replace(/&ndash;/g, "–");
  return data;
}

/**
 * 修正图片域名，部分图片可能不能直接加载
 * @param imgUrl 图片地址
 * @returns 修正后的图片地址
 */
function fixImgPrefix(imgUrl) {
  // 2018年3月31日 取消图片资源域名替换，现在可以直接正常访问图片
  // if (!imgUrl)
  return imgUrl;
  // return imgUrl.replace("pic1", "pic")
  //     .replace("pic2", "pic")
  //     .replace("pic3", "pic")
  //     .replace("pic4", "pic");
}

module.exports = {
  formatTime: formatTime,
  getCurrentData: getCurrentData,
  isFunction: isFunction,
  getHost: getHost,
  parseSortList: parseSortList,
  parseSearchResultList: parseSearchResultList,
  decodeHtml: decodeHtml,
  parseNovel: parseNovel,
  parseStoryContentFetchParam: parseStoryContentFetchParam,
  correctData: correctData,
  transferSign: transferSign,
  fixImgPrefix: fixImgPrefix
}

